# app/common/auth.py
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from django.conf import settings
import jwt

from app.user.models import McUser  # 你的用户模型

class WechatJWTAuthentication(BaseAuthentication):
    """
    只要在某个视图/接口上启用它，就会：
    1) 读取请求头 Authorization: Bearer <token>
    2) 用 settings.JWT_SECRET_KEY 解码
    3) 从 payload 取 openid，查库得到 McUser
    4) 返回 (user, payload)，视图里可用 request.user / request.auth['openid']
    """
    keyword = 'Bearer'

    def authenticate(self, request):
        auth = request.headers.get('Authorization')
        if not auth:
            # 没有传 Authorization 头：不通过当前认证类（交给其他认证类或匿名）
            return None

        parts = auth.split()
        if len(parts) != 2 or parts[0] != self.keyword:
            raise exceptions.AuthenticationFailed('Invalid Authorization header')

        token = parts[1]

        try:
            payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            raise exceptions.AuthenticationFailed('Token expired')
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed('Invalid token')

        openid = payload.get('openid')
        if not openid:
            raise exceptions.AuthenticationFailed('openid missing in token')

        # 查找或创建你的用户对象（建议先查，不存在再创建）
        try:
            user = McUser.objects.get(open_id=openid)
        except McUser.DoesNotExist:
            # 不强制创建，保持严格：token 里有 openid 但用户未入库 → 可按需要创建
            # user = McUser.objects.create(open_id=openid)
            raise exceptions.AuthenticationFailed('User not found')

        # 返回 (user, auth)；auth 可放 payload，便于视图里读取 openid 等
        return (user, payload)
